﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BuscoPre.Domain;
using BuscoPre.Domain.Services;
using Newtonsoft.Json.Linq;
using System.Web;

namespace BuscoPre.Repository
{
	public class CategoriesDao
	{
		private static readonly string CategoriesRequestUri = "https://api.mercadolibre.com/sites/MLA/categories?callback=?";
		private static readonly int IndexResult = 2;

        public static List<Category> GetAll()
        {
            try
            {
                // Logica para preguntarle a la API de Mercadolibre.
                GenericRestMessageService<Category> service = new CategoriesRestMessageService();
                // La respuesta es un JArray en el indice 2 del arreglo.
                var response = ((JArray)service.Get(CategoriesRequestUri))[IndexResult];

                if (response != null)
                {
                    var categories = new List<Category>();

                    foreach (var item in response)
                    {
                        var category = new Category
                        {
                            Id = item["id"].ToString(),
                            Name = item["name"].ToString().Replace('"', ' ').Trim(),
                            Url = string.Concat(FriendlyUrl.TitleToSeoURLWithServerPath(item["name"].ToString()), "/", item["id"].ToString().Replace('"', ' ').Trim())
                        };
                        categories.Add(category);
                    }
                    return categories;
                }
              
                return null;
                
            }
            catch (Exception)
            {
                throw;
            }
        }

		private static string ToSEO(JToken item)
		{
			return string.Concat(FriendlyUrl.TitleToSeoURL(item["name"].ToString()), "/", item["id"].ToString().Replace('"', ' ').Trim());
		}
	}
}
